package br.com.fox.iebav.dao.abstractdao;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Stateless
public abstract class AbstractDAO implements IDAO {
	
	@PersistenceContext(unitName="iebav")
	protected EntityManager entityManager;
	Query q = null;
   	

	public boolean save(Object entity) {
		try {
		
			if(entity != null)
				entityManager.persist(entity);
			else
				return false;
			
			return true;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
	}
	
	public Object findOne(Integer id,String entity,String idEntity) {
		
		Object obj = null;
		
		try 
		{
			q = entityManager.createQuery("SELECT e FROM "+entity+" e WHERE e."+idEntity+" = :id");
			q.setParameter("id",id);
			obj = q.getSingleResult();			
		} 
		catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return obj;
	}
	
	public boolean update(Object entity) {
		try {
			entityManager.merge(entity);
			return true;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
	}
	
	public boolean remove(Object entity) {
		try {
			entityManager.remove(entity);
			return true;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
	}
	

	 //Função para criar hash da senha informada  
	   public static String md5(String senha) 
	   {  
		   try 
	       {  
			   MessageDigest md = MessageDigest.getInstance("MD5");  
	           BigInteger hash = new BigInteger(1, md.digest(senha.getBytes()));  
	           return  hash.toString(16);           
	       }
		   catch (NoSuchAlgorithmException  e)
	       {  
			   e.printStackTrace();  
	       	   return "null";
	       }  
	   }  
	
}
